package com.example.design.ddd.practice2.application.order;

import com.example.design.ddd.practice2.domain.Payment.entity.Payment;
import com.example.design.ddd.practice2.domain.Payment.valueobject.PaymentRequest;
import com.example.design.ddd.practice2.domain.order.entity.Order;
import com.example.design.ddd.practice2.domain.order.entity.OrderItem;
import com.example.design.ddd.practice2.domain.order.repository.OrderRepository;
import com.example.design.ddd.practice2.domain.order.valueobject.Address;
import com.example.design.ddd.practice2.domain.shipping.repository.ShippingRepository;
import com.example.design.shejimoshi.structure.facade.PaymentService;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 协调领域对象，封装跨实体业务
 */
public class OrderApplicationService {
    private final OrderRepository orderRepository;
    private final PaymentService paymentService;
    private final ShippingRepository shippingRepository;

    public OrderApplicationService(OrderRepository orderRepository, PaymentService paymentService, ShippingRepository shippingRepository) {
        this.orderRepository = orderRepository;
        this.paymentService = paymentService;
        this.shippingRepository = shippingRepository;
    }

    @Transactional
    public String placeOrder(String userId, List<OrderItem> items, Address address) {
        // 协调领域对象
        Order order = Order.create(userId, items, address);
        // 基础设施层持久化
        orderRepository.save(order);
        return order.getOrderId();
    }

    @Transactional
    public void payOrder(String orderId, PaymentRequest request) {
        // 协调领域对象
        Order order = orderRepository.findById(orderId);
        // 协调领域对象
        Payment payment = paymentService.createPayment(order, request);
        // 跨实体业务
        order.pay(payment);
        // 基础设施层持久化
        orderRepository.save(order);
    }
}
